<?php
namespace Controller;

use Slim\Http\Request;
use Slim\Http\Response;
use Slim\Container;

class Weichat extends Base
{
    public function __construct(Container $container)
    {

        parent::__construct($container);


    }

    public function redirect(Request $req, Response $res)
    {
        $code = $req->getParam('code');


        $weichat = $this->weichat;
        $data = [
            'appid' => $weichat['appid'],
            'secret' => $weichat['appsecret'],
            'code' => $code,
            'grant_type' => 'authorization_code'

        ];
        $curl = $this->curl->get('https://api.weixin.qq.com/sns/oauth2/access_token', $data);
        if ($curl->error) {
            $this->logger->addInfo('error', $curl->error_code);
            exit;
        } else {
            $result = json_decode($curl->response, true);

            if (array_key_exists('errcode', $result)) {
                $this->logger->addInfo('info', $result);
                exit;

            } else {

                //查询是否是注册会员
                $this->redis->setex('tcp_token', $result['expires_in'], $result['access_token']);
                $openid=$result["openid"];
                $_SESSION['openid'] = $openid;
                $usercurl = $this->curl->get('https://api.weixin.qq.com/sns/userinfo', ['access_token'=>$result['access_token'],'openid'=>$openid ,'lang'=>'zh_CN']);
                $userresult = json_decode($usercurl->response, true);
                if (array_key_exists('errcode', $userresult)) {
                    $this->logger->addInfo('info', $userresult);
                    exit;

                }else{
                    $_SESSION['headimg']=$userresult['headimgurl'];
                    $where['openid'] = array("'$openid'");
                    $user = $this->db->where($where)->find('tcp_user');
                    if (!empty($user)) {
                        $_SESSION['uid']=$user['uid'];
                        if($req->getParam('state')==='/register'){
                            return  $res->withRedirect('/index');     exit;
                        }else{
                            return  $res->withRedirect($req->getParam('state'));     exit;
                        }

                    } else {
                        return  $res->withRedirect('/register');     exit;
                    }
                }


            }

        }


    }


}